package br.com.kapa.dao;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless(mappedName="bean/daojpa")
public class DaoJpaBean<T> implements DaoJpaBeanRemote<T>, Serializable {

	private static final long serialVersionUID = 1L;
	@PersistenceContext(unitName="industriaEJB") protected EntityManager em;
	
	@Override
	public void persist(Object obj) {
		em.persist(obj); 
	}
	
	@Override
	public void remove(Object obj) {
		em.remove(obj);
		em.flush();
	}
	
	@Override
	public void merge(Object obj) {
		em.merge(obj); 
	}	
	
	@SuppressWarnings("unchecked")
	protected List<T> findAll(Class<T> classe) {
		String nome = classe.getName();
		int i = nome.lastIndexOf(".");
		nome = nome.substring(i + 1);
		Query consulta = em.createQuery("SELECT x FROM " + nome + " x ");
		return (List<T>) consulta.getResultList();
	}
	
	protected T find(Class<T> classe, Object chave) {
		return em.find(classe, chave);
	}

}
